/**
 * 易驰护运 - Approve
 * http://menger.me
 * 承运商认证
 * @桓桓
 */

'use strict';
import React from 'react';
import {StyleSheet, Text, TextInput, TouchableOpacity, View, Keyboard, ListView} from 'react-native'
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view"
import loginStyle from '../../style/loginStyle'
import {FormValidation} from '../../utils/validation/FormValidation'
import { LargePicture } from '../../components';
import {inject, observer} from 'mobx-react'

@inject('loginStore')
@observer
export default class Approve extends React.Component {
    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            loading: false,
            dataSource: [
                {bond: 'business_license', name: '营业执照：', data: '', type: 'img'},
                {bond: 'business_license_validity', name: '营业执照有效期：', data: '', type: 'day'},
                {bond: 'account_open_licence', name: '开户许可证', data: '', type: 'img'},
                {bond: 'account_open_licence_validity', name: '开户许可证时间', data: '', type: 'day'},
                {bond: 'road_transport_licence', name: '道路运输许可证', data: '', type: 'img'},
                {bond: 'road_transport_licence_validity', name: '道路运输许可证时间', data: '', type: 'day', space: true},
                {type: 'space'},
                {bond: 'company_name', name: '企业全称：', data: '', placeholder: '请和营业执照保持一致', type: 'input'},
                {bond: 'company_reg_address', name: '公司注册所在地：', data: '', type: 'area'},
                {bond: 'company_address', name: '公司详细地址：', data: '', placeholder: '请输入公司详细地址', type: 'input', space: true},
                {type: 'space'},
                {bond: 'company_tax_number', name: '公司税号：', data: '', placeholder: '请输入公司税号', type: 'input'},
                {bond: 'bank_account', name: '银行账号：', data: '', placeholder: '请输入公司公户银行卡号', type: 'input'},
                {bond: 'bank_open', name: '开户行：', data: '', placeholder: '请输入开户行名称', type: 'input', space: true},
                {type: 'space'},
                {bond: 'name', name: '联系人姓名：', data: '', placeholder: '请输入联系人姓名', type: 'input'},
                {bond: 'mobile', name: '联系方式：', data: '', placeholder: '请输入联系人联系方式', type: 'input'},
                {bond: 'member_type', data: 1},
            ],
            // 营业执照
            business_license: '',
            road_transport_licence: '',
            account_open_licence: '',
            // 公司注册所在地
            province: '',
            city: '',
            district: '',
            // 营业执照有效期
            year1: '',
            month1: '',
            day1: '',
            // 开户许可证有效期
            year2: '',
            month2: '',
            day2: '',
            // 道路运输许可证有效期
            year3: '',
            month3: '',
            day3: '',
        }
    }

    componentDidMount() {
        this.updateUserInfo()
    }

    // 把之前的数据放进页面
    updateUserInfo = () => {
        let {loginStore} = this.props;
        let {userInfo, getJSDataSources} = loginStore;
        console.log('getJSDataSources(userInfo)------------->', getJSDataSources(userInfo))
        let { dataSource } = this.state;
        let dataSourceTemp = dataSource.slice();
        dataSourceTemp.forEach((item) => {
            switch (item.bond) {
                case 'business_license': // 营业执照的上传
                    this.setState({business_license: userInfo.business_license});
                    break;
                case 'business_license_validity': // 营业执照有效期
                    this.setState({
                        year1: userInfo.business_license_validity.slice(0, 4),
                        month1: userInfo.business_license_validity.slice(5, 7),
                        day1: userInfo.business_license_validity.slice(8, 10),
                    });
                    break;
                case 'account_open_licence': // 开户许可证的上传
                    this.setState({account_open_licence: userInfo.account_open_licence});
                    break;
                case 'account_open_licence_validity': // 开户许可证有效期
                    this.setState({
                        year2: userInfo.account_open_licence_validity.slice(0, 4),
                        month2: userInfo.account_open_licence_validity.slice(5, 7),
                        day2: userInfo.account_open_licence_validity.slice(8, 10),
                    });
                    break;
                case 'road_transport_licence': // 道路运输许可证的上传
                    this.setState({road_transport_licence: userInfo.road_transport_licence});
                    break;
                case 'road_transport_licence_validity': // 道路运输许可证有效期
                    this.setState({
                        year3: userInfo.road_transport_licence_validity.slice(0, 4),
                        month3: userInfo.road_transport_licence_validity.slice(5, 7),
                        day3: userInfo.road_transport_licence_validity.slice(8, 10),
                    });
                    break;
                case 'company_name':
                    this.updateState(item.bond, userInfo.company_name);
                    break;
                case 'company_reg_address': // 公司注册所在地
                    this.setState({
                        province: userInfo.company_reg_province,
                        city: userInfo.company_reg_city,
                        district: userInfo.company_reg_district,
                    });
                    break;
                case 'company_address': 
                    this.updateState(item.bond, userInfo.company_address);
                    break;
                case 'company_tax_number':
                    this.updateState(item.bond, userInfo.company_tax_number);
                    break;
                case 'bank_account':
                    this.updateState(item.bond, userInfo.bank_account);
                    break;
                case 'bank_open':
                    this.updateState(item.bond, userInfo.bank_open);
                    break;
                case 'name':
                    this.updateState(item.bond, userInfo.name);
                    break;
                case 'mobile':
                    this.updateState(item.bond, userInfo.mobile);
                    break;
                default:
                    break;
            }
        });
        this.setState({
            dataSource: dataSourceTemp,
            loading: false,
        });
    };

    // 时间选择
    showActionTimePicker = (type) => {
        Keyboard.dismiss();
        let params = {
            onPress: (value) => {
                if (type == 1) {
                    this.setState({
                        year1: value.year,
                        month1: value.month,
                        day1: value.day,
                    })    
                } else if (type == 2) {
                    this.setState({
                        year2: value.year,
                        month2: value.month,
                        day2: value.day,
                    }) 
                } else if (type == 3) {
                    this.setState({
                        year3: value.year,
                        month3: value.month,
                        day3: value.day,
                    }) 
                }
            },
            option: {
                panGestureEnabled: false,
            }
        }
        ActionManager.showWheelDate(params);
    };

    // 地址选择
    showActionAreaPicker = (type) => {
        Keyboard.dismiss();
        let params = {
            // showArea: false,
            onCallBack: (selectedData, addressText) => {
                this.setState({
                    province: selectedData.province.name,//省
                    city: selectedData.city.name,//市
                    district: selectedData.area.name,//区
                }); 
            },
            option: {
                panGestureEnabled: false,
            }
        }
        ActionManager.showCityTree(params);
    };

    // 上传图片
    onPressUpImg = async (type) => {
        Keyboard.dismiss();
        let _result = await MediaManager.showActionPicker({
            includeBase64: true,
        });
        if (_result && _result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.loading('上传中...', {duration: 9999999});
            const upRes = await Services.uploadQiNiu(_result.data);
            if (upRes.code === StatusCode.SUCCESS_CODE) {
                ToastManager.hide();
                ToastManager.success('上传成功');
                if (type == 1) {
                    this.setState({business_license: ServicesApi.QI_NIU_HOST + upRes.data[0].key});
                } else if (type == 2) {
                    this.setState({road_transport_licence: ServicesApi.QI_NIU_HOST + upRes.data[0].key});
                } else if (type == 3) {
                    this.setState({account_open_licence: ServicesApi.QI_NIU_HOST + upRes.data[0].key});
                }
            } else {
                ToastManager.fail('上传失败');
            }
        }
    };

    // 删除
    deleteImg = (type) => {
        Keyboard.dismiss();
        if (type == 1) {
            this.setState({business_license: ''})
        } else if (type == 2) {
            this.setState({road_transport_licence: ''})
        } else if (type == 3) {
            this.setState({account_open_licence: ''})
        }
    }

    // 修改数据
    updateState = (bond, data, showData, refresh) => {
        let { dataSource } = this.state;
        let index = dataSource.findIndex((item) => item.bond === bond);
        if (index !== -1) {
            let newItem = dataSource[index];
            newItem['data'] = data;
            newItem['showData'] = showData ? showData : data;
            if (refresh) {
                let newDataSource = dataSource.slice();
                newDataSource[index] = newItem;
                this.setState({ dataSource: newDataSource });
            } else {   
                dataSource[index] = newItem;
            }
        }
    };

    // 渲染的具体页面
    ListView = (dataSource) => {
        let {business_license, road_transport_licence, account_open_licence, province, city, district, year1, month1, day1, year2, month2, day2, year3, month3, day3} = this.state;
        let contain = dataSource.map((item, index) => {
            if (item.type == 'input') {
                return (
                    <View key={index} style={[styles.inputLine, item.space == true && {borderBottomWidth: 0}]}>
                        <Text style={styles.inputLineLeft} numberOfLines={1}>{item.name}</Text>
                        <TextInput
                            defaultValue={item.data}
                            style={styles.inputLineRight}
                            placeholder={item.placeholder}
                            placeholderTextColor={'#999'}
                            onChangeText={(text) => this.updateState(item.bond, text)} 
                        />
                    </View>
                )
            } else if (item.type == 'img') {
                if (item.bond == 'business_license') {
                    return (
                        <View key={index} style={[styles.inputLine, {height: 90}]}>
                            <Text style={styles.inputLineLeft} numberOfLines={1}>{item.name}</Text>
                            <TouchableOpacity onPress={() => this.onPressUpImg(1)}>
                                {
                                    business_license
                                    ?
                                    <View>
                                        <LargePicture 
                                            resizeMode={'cover'} 
                                            style={styles.inputUpImg} 
                                            imageStyle={styles.inputUpImg} 
                                            source={{uri: business_license}}
                                        /> 
                                        <TouchableOpacity style={styles.deleteImgBox} onPress={() => this.deleteImg(1)}>
                                            <ImageView resizeMode={'contain'} style={styles.deleteImg} source={Images.icon_result_fail}/>
                                        </TouchableOpacity>
                                    </View>
                                    :
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.inputUpImg}
                                        source={Images.img_uploadimg8}
                                    />
                                }
                            </TouchableOpacity>
                        </View>
                    )
                } else if (item.bond == 'road_transport_licence') {
                    return (
                        <View key={index} style={[styles.inputLine, {height: 90}]}>
                            <Text style={styles.inputLineLeft} numberOfLines={1}>{item.name}</Text>
                            <TouchableOpacity onPress={() => this.onPressUpImg(2)}>
                                {
                                    road_transport_licence
                                    ?
                                    <View>
                                        <LargePicture 
                                            resizeMode={'cover'} 
                                            style={styles.inputUpImg} 
                                            imageStyle={styles.inputUpImg} 
                                            source={{uri: road_transport_licence}}
                                        /> 
                                        <TouchableOpacity style={styles.deleteImgBox} onPress={() => this.deleteImg(2)}>
                                            <ImageView resizeMode={'contain'} style={styles.deleteImg} source={Images.icon_result_fail}/>
                                        </TouchableOpacity>
                                    </View>
                                    :
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.inputUpImg}
                                        source={Images.img_uploadimg6}
                                    />
                                }
                            </TouchableOpacity>
                        </View>
                    )
                } else if (item.bond == 'account_open_licence') {
                    return (
                        <View key={index} style={[styles.inputLine, {height: 90}]}>
                            <Text style={styles.inputLineLeft} numberOfLines={1}>{item.name}</Text>
                            <TouchableOpacity onPress={() => this.onPressUpImg(3)}>
                                {
                                    account_open_licence
                                    ?
                                    <View>
                                        <LargePicture 
                                            resizeMode={'cover'} 
                                            style={styles.inputUpImg} 
                                            imageStyle={styles.inputUpImg} 
                                            source={{uri: account_open_licence}}
                                        /> 
                                        <TouchableOpacity style={styles.deleteImgBox} onPress={() => this.deleteImg(3)}>
                                            <ImageView resizeMode={'contain'} style={styles.deleteImg} source={Images.icon_result_fail}/>
                                        </TouchableOpacity>
                                    </View>
                                    :
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.inputUpImg}
                                        source={Images.img_uploadimg7}
                                    />
                                }
                            </TouchableOpacity>
                        </View>
                    )
                }
            } else if (item.type == 'day') {
                if (item.bond == 'business_license_validity') {
                    return (
                        <View key={index} style={[styles.inputLine, item.space == true && {borderBottomWidth: 0}]}>
                            <Text style={styles.inputLineLeft} numberOfLines={1}>{item.name}</Text>
                            <TouchableOpacity style={styles.inputDay} onPress={() => this.showActionTimePicker(1)}>
                                <Text style={[styles.inputDayText, year1 !== '' && {color: '#333'}]} numberOfLines={1}>
                                    {year1 == '' ? '请选择有效期' : year1+'-'+month1+'-'+day1}    
                                </Text>
                                <ImageView
                                    resizeMode={'contain'}
                                    style={styles.inputDayImg}
                                    source={Images.icon_arrow_right}
                                />
                            </TouchableOpacity>
                        </View>
                    )
                } else if (item.bond == 'road_transport_licence_validity') {
                    return (
                        <View key={index} style={[styles.inputLine, item.space == true && {borderBottomWidth: 0}]}>
                            <Text style={styles.inputLineLeft} numberOfLines={1}>{item.name}</Text>
                            <TouchableOpacity style={styles.inputDay} onPress={() => this.showActionTimePicker(2)}>
                                <Text style={[styles.inputDayText, year2 !== '' && {color: '#333'}]} numberOfLines={1}>
                                    {year2 == '' ? '请选择有效期' : year2+'-'+month2+'-'+day2}    
                                </Text>
                                <ImageView
                                    resizeMode={'contain'}
                                    style={styles.inputDayImg}
                                    source={Images.icon_arrow_right}
                                />
                            </TouchableOpacity>
                        </View>
                    )
                } else if (item.bond == 'account_open_licence_validity') {
                    return (
                        <View key={index} style={[styles.inputLine, item.space == true && {borderBottomWidth: 0}]}>
                            <Text style={styles.inputLineLeft} numberOfLines={1}>{item.name}</Text>
                            <TouchableOpacity style={styles.inputDay} onPress={() => this.showActionTimePicker(3)}>
                                <Text style={[styles.inputDayText, year3 !== '' && {color: '#333'}]} numberOfLines={1}>
                                    {year3 == '' ? '请选择有效期' : year3+'-'+month3+'-'+day3}    
                                </Text>
                                <ImageView
                                    resizeMode={'contain'}
                                    style={styles.inputDayImg}
                                    source={Images.icon_arrow_right}
                                />
                            </TouchableOpacity>
                        </View>
                    ) 
                }
            } else if (item.type == 'area') {
                return (
                    <View key={index} style={styles.inputLine}>
                        <Text style={styles.inputLineLeft} numberOfLines={1}>{item.name}</Text>
                        <TouchableOpacity style={styles.inputDay} onPress={() => this.showActionAreaPicker()}>
                            <Text style={[styles.inputDayText, province !== '' && {color: '#333'}]} numberOfLines={1}>
                                {province == '' ? '请选择省/市/区' : province+'-'+city+'-'+district}
                            </Text>
                            <ImageView
                                resizeMode={'contain'}
                                style={styles.inputDayImg}
                                source={Images.icon_arrow_right}
                            />
                        </TouchableOpacity>
                    </View>
                )
            } else if (item.type == 'space') {
                return (
                    <View key={index} style={styles.spaceLine}></View>
                )
            }
        })
        return contain
    }

    // 提交
    onSubmit = async () => {
        Keyboard.dismiss();
        let {dataSource, business_license, road_transport_licence, account_open_licence, province, city, district, year1, month1, day1, year2, month2, day2, year3, month3, day3} = this.state;
        if (province == '') {
            ToastManager.message('请选择公司注册所在地')
            return 
        }
        if (year1 == '') {
            ToastManager.message('请选择营业执照有效期')
            return 
        }
        if (year2 == '') {
            ToastManager.message('请选择开户许可证有效期')
            return 
        }
        if (year3 == '') {
            ToastManager.message('请选择道路运输许可证有效期')
            return 
        }
        let url = ServicesApi.LOGIN_AUTHENTICATION;
        let data = {};
        dataSource.forEach((item) => { // 把数据遍历进data
            if (item.bond === 'business_license') { // 营业执照
                data['business_license'] = business_license
            } else if (item.bond === 'road_transport_licence') {
                data['road_transport_licence'] = road_transport_licence
            } else if (item.bond === 'account_open_licence') {
                data['account_open_licence'] = account_open_licence
            } else if (item.bond === 'business_license_validity') { // 营业执照有效期
                data['business_license_validity'] = year1 +'-'+ month1 +'-'+ day1;
            } else if (item.bond === 'road_transport_licence_validity') {
                data['road_transport_licence_validity'] = year2 +'-'+ month2 +'-'+ day2;
            } else if (item.bond === 'account_open_licence_validity') {
                data['account_open_licence_validity'] = year3 +'-'+ month3 +'-'+ day3;
            } else if (item.bond === 'company_reg_address') { // 公司注册所在地
                data['company_reg_province'] = province;
                data['company_reg_city'] = city;
                data['company_reg_district'] = district;
                data['type'] = 2; // 承运商
            } else {
                data[item.bond] = item.data
            }
        });
        let result = await Services.post(url, data);
        if (result.code == StatusCode.SUCCESS_CODE) {
            ToastManager.success('提交认证成功');
            setTimeout(()=> {
                RouterHelper.reset('', 'Tab');
            }, 1000);
        } else if (result.code === StatusCode.FAIL_CODE) {
            ToastManager.warn(result.msg)
        }
    }

    render() {
        let {loginStore} = this.props;
        let {userInfo} = loginStore;
        let {loading, dataSource} = this.state;
        return (
            <PageContainer
                loading={loading}
                fitNotchedScreen={Predefine.isNotchedScreen}
                style={styles.container}
            >
                <NavigationBar 
                    title={'承运商认证'} 
                    style={styles.navigationBar}
                    // renderRightAction={[{title: <Text style={styles.rightAction}>暂不认证</Text>, onPress: () => RouterHelper.navigate('', 'Login')}]}
                />
                <KeyboardAwareScrollView
                    keyboardShouldPersistTaps={'handled'}
                    style={styles.contentBoxStyle}
                >
                    {
                        userInfo.is_pass == 0 &&
                        <View style={styles.reasonsBox}>
                            <ImageView
                                resizeMode={'contain'}
                                style={styles.reasonsImg}
                                source={Images.icon_warring_logo1}
                            />
                            <Text style={styles.reasons}>拒绝原因：{userInfo.reasons}</Text>
                        </View>
                    }
                    {this.ListView(dataSource)}
                    <View style={styles.btnBox}>
                        <Button
                            style={styles.btn}
                            title={'提交认证'}
                            titleStyle={styles.btnTitle}
                            resizeMode={'cover'}
                            backgroundImage={Images.img_btn_bg1}
                            onPress={() => this.onSubmit()}
                        />
                    </View>
                </KeyboardAwareScrollView>
            </PageContainer>
        );
    }
}

const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    rightAction: {
        color: '#fff',
        fontSize: 15,
    },

    reasonsBox: {
        backgroundColor: '#e1e1e1',
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 15,
        paddingVertical: 10,
    },
    reasonsImg: {
        width: 16,
        height: 16,
        marginRight: 6,
    },
    reasons: {
        fontSize: 14,
        color: '#333',
    },
    inputLine: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 50,
        marginHorizontal: 15,
        borderBottomWidth: Predefine.minPixel,
        borderBottomColor: '#e1e1e1',
    },
    inputLineLeft: {
        color: '#333',
        fontSize: 14,
    },
    inputLineRight: {
        color: '#666',
        fontSize: 14,
        flex: 1,
        textAlign: 'right',
    },
    inputDay: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
    },
    inputDayText: {
        color: '#999',
        fontSize: 14,
        flex: 1,
        textAlign: 'right',
        marginHorizontal: 6,
    },
    inputDayImg: {
        width: 12,
        height: 12,
    },
    inputUpImg: {
        width: 120,
        height: 72,
    },
    spaceLine: {
        height: 10,
        backgroundColor: '#F2F1F6',
    },

    deleteImgBox: {
        position: 'absolute',
        top: -8,
        right: -8,
    },
    deleteImg: {
        width: 16,
        height: 16,
        borderRadius: 8,
    },

    btnBox: {
        padding: 30,
    },
    btn: {
        backgroundColor: DominantColor,
    },
});